# configure-tftp.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
package CCNCore::Provision::phones_cisco;
use strict;
use warnings;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;
use CCN::TimeOffset;

sub run()
{
    my $self = shift;
    return unless $self->p->is_a_file_server;

    $self->PACKAGE ('unzip');

    mkdir CCNCore::Home::config.'/local/loads'
        unless -d CCNCore::Home::config.'/local/loads';
    mkdir CCNCore::Home::config.'/local/loads/cisco'
        unless -d CCNCore::Home::config.'/local/loads/cisco';
    mkdir CCNCore::Home::tftpboot.'/dialplan'
        unless -d CCNCore::Home::tftpboot.'/dialplan';

    my %ciscosip = ();

    $self->sql_do_for(<<'SQL',$self->p->server_pk,
        SELECT  pool.pk, pool.enterprise, enterprise.salt, pool.timezone, pool.timeformat,
                pool.expire, pool.cp_cluster, pool.px_cluster
        FROM pool, enterprise
        WHERE pool.pk IN (SELECT pool FROM pool_server WHERE server = ? AND role = 'file')
        AND enterprise.pk = pool.enterprise;
SQL
    sub
    {
        my ($POOL_pk,$ENTERPRISE_pk,$SALT,$tz_name,$CLOCK_24,$REGISTER_EXPIRE,$cp_cluster,$register_cluster) = @_;

        $tz_name = $self->sql_get(q(SELECT timezone FROM systems WHERE pk = ?),$self->p->system_pk)
            if not defined $tz_name;
        $tz_name = 'UTC' if not defined $tz_name;
        my $GMT_OFFSET = CCN::TimeOffset::time_offset($tz_name);
        my $GMT_OFFSET_SEC = 3600*${GMT_OFFSET};

        $REGISTER_EXPIRE ||= 60;

        $self->sql_do_for(<<'SQL',$POOL_pk,
            SELECT pk, mac, ciscosip
            FROM phone WHERE type = 'cisco' AND pk = ?
SQL
        sub
        {
            my ($phone_pk,$MAC,$CISCO_SIP) = @_;
            $MAC = CCN::Text::mac_from_dotted($MAC);

            my $LINE_APPEARANCES    = '';

            $ciscosip{$CISCO_SIP} = 1 if defined $CISCO_SIP;
            $self->warn ("Cisco SIP load not specified for MAC ${MAC}.")
                if not defined $CISCO_SIP;
            $CISCO_SIP ||= '';
            $CISCO_SIP = "image_version: $CISCO_SIP" if $CISCO_SIP ne '';

            # Generate configuration files
            my $line = 0;

            $self->sql_do_for(<<'SQL',$phone_pk,
                SELECT rank, "number", label, keys, "login", "password"
                FROM "line" WHERE phone = ? ORDER BY rank ASC
SQL
            sub
            {
                my ($LINE,$NUMBER,$LABEL,$KEYS,$LOGIN,$password) = @_;
                $line++;

                # These should always be defined (by the parser).

                $LABEL = $NUMBER if not defined $LABEL;

                # See db_ser.pm
                # my $password = substr($self->make_password(${ENTERPRISE_pk},${SALT},${LOGIN},'phone'),12,12);

                my $REGISTER_SERVER = $self->p->make_cluster_name(${register_cluster},'px');
                my $REGISTER_PORT = '';

                $LINE_APPEARANCES .= <<"EOT";
proxy${line}_address: "$REGISTER_SERVER"
proxy${line}_port: $REGISTER_PORT
line${line}_name: $LOGIN
line${line}_displayname: $LABEL
line${line}_shortname: $NUMBER
line${line}_authname: $LOGIN
line${line}_password: $password
EOT
                # For speed dial lines, we have:
                # speed_line${line} = "$SPEED_DIAL"
                # speed_label${line} = "$LABEL"
            }); # foreach @lines

            my $XML_SERVER          = '';
            my $DIALPLAN_DIGITMAP   = '';
            $CLOCK_24 = 1 if not defined $CLOCK_24;
            $CLOCK_24 = 1 if $CLOCK_24 =~ /^t/i;
            $CLOCK_24 = 0 if $CLOCK_24 =~ /^f/i;

            # TBD FIXME
            my $SNTP_SERVER = $self->sql_get(q(SELECT server FROM pool_server WHERE role = 'dhcp' AND pool = ?),$POOL_pk);
            $SNTP_SERVER = $self->p->server_pk if not defined $SNTP_SERVER;

            $SNTP_SERVER = $self->primary_ip($SNTP_SERVER);

            my $uMAC = uc($MAC);
            foreach ("/home/tftpboot/dialplan/${uMAC}.xml")
            {
                # YYY Build digitmap and output it.
            }

            my $PROXY_SERVER = $self->p->make_cluster_name(${register_cluster},'px');
            my $PROXY_PORT = '';

            my $context =
            {
                'XML_SERVER' => $XML_SERVER,
                'PROXY_SERVER' => $PROXY_SERVER,
                'PROXY_PORT' => $PROXY_PORT,
                'CLOCK_24' => $CLOCK_24,
                'SNTP_SERVER' => $SNTP_SERVER,
                'uMAC' => $uMAC,
                'REGISTER_EXPIRE' => $REGISTER_EXPIRE,
                'LINE_APPEARANCES' => $LINE_APPEARANCES,
                'CISCO_SIP' => $CISCO_SIP,
                'tz_name' => $tz_name,
            };

            foreach ("/home/tftpboot/SIP${uMAC}.cnf")
            {
                template(CCNCore::Home::manager.'/lib/templates/cisco-phone.txt',$_,$context);
            }
        });
    }); # for @pools

    foreach(CCNCore::Home::config.'/local/bin/install-cisco.sh')
    {
        my $LOADS = join(' ',keys %ciscosip) || '';
        my $home_config = CCNCore::Home::config;

        my $TFTPBOOT = CCNCore::Home::tftpboot;

        CAT $_, copyright('#!/bin/sh').<<"EOT";
# This script unzips the firmware loads from Cisco and
# installs them in the proper location.

# For testing purposes
TFTPBOOT=${TFTPBOOT}

echo "Installing Cisco loads into \$TFTPBOOT/"
for LOAD in ${LOADS};
do
    echo "Unzip \$LOAD"
    unzip -q -o "\$ROOT$home_config/local/loads/cisco/\${LOAD}.zip" \\
        '*.bin' '*.sbn' '*.sb2' '*.loads' \\
        -d "\$TFTPBOOT/" || exit 1
done

echo "Updating ownership"
# chown -R \$who \$TFTPBOOT/

EOT

        IF_CHANGED $_ => "/bin/sh $_";
    }
}

1;